package com.xyd.Servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.xyd.Service.ProductService;
import com.xyd.bean.ChildCategory;
import com.xyd.bean.ParentCategory;
import com.xyd.bean.Product;
import org.apache.commons.io.FileUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/admin/product","/manage/admin/getParent","/manage/admin/getChild","/manage/admin/addProduct",
               "/admin/productDetail","/admin/productModify","/admin/productDel"})
public class AdminManageProductServlet extends HttpServlet {
    ProductService productService = new ProductService();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/admin/product".equals(path)){
            doGetAll(request,response);
        }else if ("/manage/admin/getParent".equals(path)){
            doGetParent(request,response);
        }else if ("/manage/admin/getChild".equals(path)){
            doGetChild(request,response);
        }else if ("/manage/admin/addProduct".equals(path)){
            doAddProduct(request,response);
        }else if ("/admin/productDetail".equals(path)){
            doDetail(request,response);
        }else if ("/admin/productModify".equals(path)){
            doModify(request,response);
        }else if ("/admin/productDel".equals(path)){
            doDel(request,response);
        }
    }

    private void doDel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id  =request.getParameter("id");
        int i = productService.delProduct(Integer.valueOf(id));
        if (i > 0){
            response.sendRedirect("/admin/product");
        }
    }

    private void doModify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ParentCategory parentCategory = new ParentCategory();
        ChildCategory childCategory = new ChildCategory();
        Product product =new Product();
       String id  =request.getParameter("id");
       String name = request.getParameter("name");
        String parendId = request.getParameter("parentId");
        String childId = request.getParameter("childId");
        String price = request.getParameter("price");
        String stock = request.getParameter("stock");

//       String filename= request.getParameter("filename");
        parentCategory.setParentid(Integer.parseInt(parendId));
        childCategory.setChildid(Integer.parseInt(childId));
        product.setId(Integer.parseInt(id));
        product.setName(name);
        product.setParentCategory(parentCategory);
        product.setChildCategory(childCategory);
        product.setPrice(Double.parseDouble(price));
        product.setStock(Integer.parseInt(stock));
        int i = productService.modifyProduct(product);
        if (i >0){
            response.sendRedirect("/manage/manage-result.html");
        }
    }

    //获取某个商品详情
    private void doDetail(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        Product product = productService.getById(Integer.parseInt(id));
        if (product != null){
            request.setAttribute("product",product);
            request.getRequestDispatcher("/manage/product-modify.jsp").forward(request,response);
        }

    }

    //添加商品
    private void doAddProduct(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        SmartUpload sm = new SmartUpload();
        ParentCategory parentCategory = new ParentCategory();
        ChildCategory childCategory = new ChildCategory();
      /*  sm.initialize(this.getServletConfig(), request, response);
        sm.setCharset("UTF-8");
        try {
            sm.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        Request smRequest = sm.getRequest();*/
        String name = request.getParameter("name");
        String parentId = request.getParameter("parentId");
        String childId = request.getParameter("childId");
        double price = Double.parseDouble(request.getParameter("price"));;
        String desc = request.getParameter("desc");
        int stock = Integer.parseInt(request.getParameter("stock"));
        String filename = request.getParameter("filename");
        parentCategory.setParentid(Integer.parseInt(parentId));
        childCategory.setChildid(Integer.parseInt(childId));
        Product product = new Product(name,desc,price,stock,parentCategory,childCategory,filename);
       /* try {
            sm.save("/upfiles");
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }*/
        int i = productService.addProduct(product);
        if (i>0){
            response.sendRedirect("/admin/product");
        }

    }

    //根据一级分类填充二级分类的下拉列表
    private void doGetChild(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String parentId = request.getParameter("parentId");
        List<ChildCategory> childCategories = productService.getByParentId(Integer.parseInt(parentId));
        if (childCategories.size()>0){
            ObjectMapper om = new ObjectMapper();
            String json = om.writeValueAsString(childCategories);
            response.getWriter().print(json);
        }
    }

    //获取所有一级分类
    private void doGetParent(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        List<ParentCategory> parentCategories = productService.getParentAll();
        if (parentCategories.size()>0){
            response.setContentType("text/html;charset=utf-8");
            request.getSession().setAttribute("parents",parentCategories);
            ObjectMapper om = new ObjectMapper();
            String json = om.writeValueAsString(parentCategories);
            response.getWriter().print(json);
        }
    }

    private void doGetAll(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Product> products = productService.getAll();
        HttpSession session = request.getSession();
        if (products.size()>0){
            session.setAttribute("products",products);
            request.getRequestDispatcher("/manage/product.jsp").forward(request,response);
        }
    }
}
